import org.apache.log4j.Logger;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

public class ScheduleUtil {
    private static  Logger LOG=Logger.getLogger(ScheduleUtil.class.getClass());

    private static ThreadPoolTaskScheduler taskScheduler=new ThreadPoolTaskScheduler();
    private static Map<Integer, ScheduledFuture<?>> scheduledFutureMap=new HashMap<>();

    static {
        taskScheduler.initialize();
        LOG.info("定时任务线程池启动");
        System.out.println("定时任务线程池启动");
    }

    /**
     * 启动某定时任务
     * @param scheduleTask
     * @param startTime
     */
    public static void start(ScheduleTask scheduleTask, Date startTime){
        ScheduledFuture<?> schedule = taskScheduler.schedule(scheduleTask, startTime);
        scheduledFutureMap.put(scheduleTask.getId(),schedule);
        LOG.info("启动定时任务"+scheduleTask.getId()+",执行时间为"+startTime);
        System.out.println("启动定时任务" + scheduleTask.getId() + ",执行时间为" + startTime);
    }

    /**
     * 取消某定时任务
     * @param scheduleTask
     */
    public static void cancel(ScheduleTask scheduleTask){
        ScheduledFuture<?> future = scheduledFutureMap.get(scheduleTask.getId());
        if(future!=null&&!future.isCancelled()){
            future.cancel(false);
        }
        scheduledFutureMap.remove(scheduleTask.getId());
        LOG.info("取消定时任务:"+scheduleTask.getId());
        System.out.println("取消定时任务:" + scheduleTask.getId());
    }

    /**
     * 修改定时任务
     * @param scheduleTask
     * @param startTime
     */
    public static void reset(ScheduleTask scheduleTask,Date startTime){
        //取消定时任务
        ScheduledFuture<?> future = scheduledFutureMap.get(scheduleTask.getId());
        if(future!=null&&!future.isCancelled()){
            future.cancel(false);
        }
        scheduledFutureMap.remove(scheduleTask.getId());
        //启动新的定时任务
        future = taskScheduler.schedule(scheduleTask, startTime);
        scheduledFutureMap.put(scheduleTask.getId(),future);
        LOG.info("修改定时任务"+scheduleTask.getId()+",执行时间为"+ startTime);
        System.out.println("修改定时任务" + scheduleTask.getId() + ",执行时间为" + startTime);
    }

}
